import React, {useEffect, useState} from 'react'
import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import './NewsEditor.css'

export default function NewsEditor(props) {
    // console.log(EditorState.createEmpty())
    const [editorState, setEditorState] = useState("") // EditorState.createEmpty()

    useEffect(()=>{
        if(props.content) {
            const contentBlock= htmlToDraft(props.content);
            if(contentBlock) {
                const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
                const editorState = EditorState.createWithContent(contentState);
                setEditorState(editorState);
            }
        }
    }, [props.content]);



    return (
        <div>
            <Editor
                editorState={ editorState }
                toolbarClassName="toolbarClassName"
                wrapperClassName="wrapperClassName"
                editorClassName="editorClassName"
                onEditorStateChange={(state)=>setEditorState(state)}
                onBlur={ ()=>{
                    let htmlContent= draftToHtml(convertToRaw(editorState.getCurrentContent()));
                    // console.log(htmlContent);
                    props.getContent(htmlContent);
                }}
            />
        </div>
    )

}
